package com.yuanli.cosmeticmirror.base;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.DisplayMetrics;

import androidx.annotation.Nullable;

import com.bytedance.sdk.openadsdk.TTAdConfig;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.comenjoysoft.baselibrary.base.BaseApplication;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.yuanli.cosmeticmirror.BuildConfig;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.yuanli.cosmeticmirror.bean.PhotoFrameStatus;
import com.yuanli.cosmeticmirror.utils.FileUtils;
import com.yuanli.pangolinads.holder.TTAdManagerHolder;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import me.jessyan.autosize.AutoSizeConfig;
import me.jessyan.autosize.unit.Subunits;
import me.jessyan.autosize.utils.LogUtils;
import okhttp3.OkHttpClient;
import rxhttp.wrapper.param.RxHttp;
import rxhttp.wrapper.ssl.SSLSocketFactoryImpl;
import rxhttp.wrapper.ssl.X509TrustManagerImpl;

public class MyApp extends BaseApplication {
    public static int screenWidth;
    public static int screenHeight;
    public static int POSITION = -1;
    public static int POSITION_PHOTO = -1;
    public static boolean IsVIP = false;
    public static String TAG = "cosmeticmirror2--> ";

    public static PhotoFrameStatus getPhotoFrameStatus() {
        return photoFrameStatus;
    }

    private static PhotoFrameStatus photoFrameStatus;
    public static boolean isLogin = false;

    public MyApp() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initAutoSize();
        initDialog();
        initLogger();
        initWH();
        initRxHttp();
        //        initFolder();
        initUmeng();
        //
        TTAdManagerHolder.init(this);
        photoFrameStatus = new PhotoFrameStatus();
    }


    private void initRxHttp() {
        RxHttp.init(getDefaultOkHttpClient(), true);
    }

    private OkHttpClient getDefaultOkHttpClient() {
        X509TrustManager trustAllCert = new X509TrustManagerImpl();
        SSLSocketFactory sslSocketFactory = new SSLSocketFactoryImpl(trustAllCert);
        return new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .sslSocketFactory(sslSocketFactory, trustAllCert) //添加信任证书
                .hostnameVerifier((hostname, session) -> true) //忽略host验证
                .build();
    }

    private void initWH() {
        DisplayMetrics mDisplayMetrics = getApplicationContext().getResources()
                .getDisplayMetrics();
        screenWidth = mDisplayMetrics.widthPixels;
        screenHeight = mDisplayMetrics.heightPixels;
    }

    private void initDialog() {
        DialogSettings.init();
        DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
    }

    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)  // 是否显示线程信息，默认为ture
                .methodCount(5)         // 显示的方法行数，默认为2
                .methodOffset(5)        // 隐藏内部方法调用到偏移量，默认为5
                //                    .logStrategy() // 更改要打印的日志策略。
                .tag(TAG)   // 每个日志的全局标记。默认PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }


    //    /**
    //     * 穿山甲广告
    //     */
    //    private void initPangolinAds() {
    //        //强烈建议在应用对应的Application#onCreate()方法中调用，避免出现content为null的异常
    //        TTAdSdk.init(this,
    //                new TTAdConfig.Builder()
    //                        .appId("5001121")
    //                        .useTextureView(false) //使用TextureView控件播放视频,默认为SurfaceView,当有SurfaceView冲突的场景，可以使用TextureView
    //                        .appName("化妆镜")
    //                        .titleBarTheme(TTAdConstant.TITLE_BAR_THEME_DARK)
    //                        .allowShowNotify(true) //是否允许sdk展示通知栏提示
    //                        .allowShowPageWhenScreenLock(true) //是否在锁屏场景支持展示广告落地页
    //                        //                        .debug(true) //测试阶段打开，可以通过日志排查问题，上线时去除该调用
    //                        .directDownloadNetworkType(TTAdConstant.NETWORK_STATE_WIFI, TTAdConstant.NETWORK_STATE_3G) //允许直接下载的网络状态集合
    //                        .supportMultiProcess(false) //是否支持多进程，true支持
    //                        .asyncInit(true)
    //                        //.httpStack(new MyOkStack3())//自定义网络库，demo中给出了okhttp3版本的样例，其余请自行开发或者咨询工作人员。
    //                        .build());
    //    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        LogUtils.e("onLowMemory");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        LogUtils.e("onTrimMemory");
    }

    @Override
    public void onTerminate() {
        BaseDialog.unload();
        super.onTerminate();
    }

    public void initAutoSize() {
        AutoSizeConfig.getInstance().getUnitsManager()
                .setSupportDP(true)
                .setSupportSP(true)
                .setDesignSize(1080, 1920)
                .setSupportSubunits(Subunits.NONE);


    }

    /**
     * 友盟
     */
    private void initUmeng() {
        /**
         * 设置组件化的Log开关
         * 参数: boolean 默认为false，如需查看LOG设置为true
         */
        UMConfigure.setLogEnabled(false);
        UMConfigure.init(this, "5ea5530a895cca9b2d0003bd", "UMENG_CHANNEL_MAIN", UMConfigure.DEVICE_TYPE_PHONE, "");
        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        //错误统计
        MobclickAgent.setCatchUncaughtExceptions(true);

        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                MobclickAgent.onResume(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                MobclickAgent.onPause(activity);
            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });
    }

    private void initFolder() {
        FileUtils.createFolder(Config.PHOTO_PATH);

    }
}